package main

import (
	"context"
	"fmt"
	"google.golang.org/grpc"
	"grpc-test/pb/person"
	"net"
	"time"
)

type personServer struct {
	person.UnimplementedSearchServiceServer
}

func (*personServer) Search(_ context.Context, req *person.PersonReq) (*person.PersonRes, error) {
	name := req.GetName()
	res := &person.PersonRes{Name: "我收到了" + name + "的信息"}
	return res, nil
}

func (*personServer) SearchIn(server person.SearchService_SearchInServer) error {
	for {
		req, err := server.Recv()
		fmt.Println(req)
		if err != nil {
			err = server.SendAndClose(&person.PersonRes{Name: "ok"})
			if err != nil {
				fmt.Println(err)
			}
			break
		}
	}
	return nil
}

func (*personServer) SearchOut(req *person.PersonReq, server person.SearchService_SearchOutServer) error {
	name := req.Name
	for i := 0; i < 10; i++ {
		time.Sleep(time.Second)
		err := server.Send(&person.PersonRes{Name: "我拿到了" + name + "的信息"})
		if err != nil {
			panic(err.Error())
		}
	}
	return nil
}

func (*personServer) SearchIO(server person.SearchService_SearchIOServer) error {
	str := make(chan string)
	go func() {
		for i := 0; i < 10; i++ {
			req, err := server.Recv()
			if err != nil {
				break
			}
			str <- req.Name
		}
		str <- "end"
	}()

	for {
		s := <-str
		err := server.Send(&person.PersonRes{Name: s})
		if err != nil {
			fmt.Println(err)
		}
		if s == "end" {
			break
		}
	}

	return nil
}

func main() {
	l, err := net.Listen("tcp", ":8080")
	if err != nil {
		panic(err.Error())
	}

	s := grpc.NewServer()
	person.RegisterSearchServiceServer(s, &personServer{})
	err = s.Serve(l)
	if err != nil {
		panic(err.Error())
	}
}
